const express = require('express');
const router = express.Router();
const usersDAO = require('../bin/db/usersDAO');
const md5 = require('md5');

/* GET users listing. */
router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});

router.post('/regist', function (req, res) {
    usersDAO.findOne({username: req.body.username})
        .then(function (data) {
            if (data) {
                res.json({err: 1, msg: "用户名已被占用"})
            } else {
                req.body.psw = md5(req.body.psw);
                let u = new usersDAO(req.body);
                u.save()
                    .then(function (err) {
                        res.json({err: 0, msg: "注册成功"})
                    })
            }
        })
});
//登录接口
router.post('/login', function (req, res) {
    req.body.psw = md5(req.body.psw);
    usersDAO.findOne(req.body, {psw: 0})
        .then(function (data) {
            if (!data) {
                res.json({err: 2, msg: "用户名或密码错误"})
            } else {
                req.session.user = data;
                res.json({err: 0, msg: "登录成功", data})
            }
        })
});
//退出接口
router.post('/logout',function (req,res) {
    req.session.user = null;
    res.json({err:0,msg:"退出成功"})
});
module.exports = router;
